package com.bckj.fastboot.security.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import com.bckj.fastboot.security.constant.SecurityConstants;
import com.bckj.fastboot.security.model.AuthUser;
import com.bckj.fastboot.upms.api.dto.UserAuthInfo;
import org.springframework.core.Ordered;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

public interface FastUserDetailsService extends UserDetailsService, Ordered {

    /**
     * 是否支持此客户端校验
     * @param clientId 目标客户端
     * @return true/false
     */
    default boolean support(String clientId, String grantType) {
        return true;
    }

    @Override
    default int getOrder() {
        return 0;
    }

    default AuthUser getUserDetails(UserAuthInfo userDetails) {
        Assert.notNull(userDetails, "该用户未注册");
        Set<String> dbAuthsSet = new HashSet<>();

        if (CollUtil.isNotEmpty(userDetails.getPermissions())) {
            dbAuthsSet = userDetails.getPermissions();
        }

        Collection<GrantedAuthority> authorities = AuthorityUtils
                .createAuthorityList(dbAuthsSet.toArray(new String[0]));

        // 构造security用户
        return new AuthUser(userDetails.getId(), userDetails.getDeptId(), userDetails.getUsername(),
                SecurityConstants.BCRYPT + userDetails.getPassword(), userDetails.getPhone(),
                userDetails.isEnabled(), userDetails.isAccountNonExpired(), userDetails.isCredentialsNonExpired(), userDetails.isAccountNonLocked(), authorities);
    }

    /**
     * @param user
     * @return {@link UserDetails}
     */
    default UserDetails loadByUser(AuthUser user) {
        return loadUserByUsername(user.getUsername());
    }
}
